/*******************************************************************************
 * FeedbackManagerAction.java
 *
 * Created by Ashutosh
 * Last modified Date: Nov 13, 2008 5:14:32 PM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/

package com.printeverywhere.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.FeedbackServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.Feedback;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.User;
import com.printeverywhere.dto.UserFeedbackCount;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class FeedbackManagerAction.
 */
public class FeedbackManagerAction extends AdminEngineManagement implements ServletRequestAware {

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(FeedbackManagerAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The item id. */
	private String itemId;

	/** The user id. */
	private String userId;

	/** The user id. */
	private String ratingUserId;

	/** The feedback id. */
	private int feedbackId;

	/** The buyer comment. */
	private String buyerComment = "";

	/** The seller comment. */
	private String sellerComment = "";

	/** The request. */
	private HttpServletRequest request;

	List<UserFeedbackCount> feedbackCountList = new ArrayList<UserFeedbackCount>();

	/** The feedbacks. */
	private List<Feedback> feedbacks = new ArrayList<Feedback>();

	/** The total neutral feedback. */
	private int totalNeutralFeedback;

	/** The total negative feedback. */
	private int totalNegativeFeedback;

	/** The total positive feedback. */
	private int totalPositiveFeedback;

	private int rating = -2;

	public int getTotalPositiveFeedback() {
		return totalPositiveFeedback;
	}

	public void setTotalPositiveFeedback(int totalPositiveFeedback) {
		this.totalPositiveFeedback = totalPositiveFeedback;
	}

	public int getTotalNeutralFeedback() {
		return totalNeutralFeedback;
	}

	public void setTotalNeutralFeedback(int totalNeutralFeedback) {
		this.totalNeutralFeedback = totalNeutralFeedback;
	}

	public int getTotalNegativeFeedback() {
		return totalNegativeFeedback;
	}

	public void setTotalNegativeFeedback(int totalNegativeFeedback) {
		this.totalNegativeFeedback = totalNegativeFeedback;
	}

	public List<Feedback> getFeedbacks() {
		return feedbacks;
	}

	public void setFeedbacks(List<Feedback> feedbacks) {
		this.feedbacks = feedbacks;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}

		populateUserCountList();

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public void populateUserCountList() throws Exception {

		List userFeedbackCountList = CommonFunctionDelegator.executeSQLQuery("SELECT u.userID, u.email, sum(f.positive), sum(f.negative), sum(f.neutral) FROM User u, Feedback f where u.id = f.to_user_id group by userId");

		for (Object object : userFeedbackCountList) {
			Object[] objectArray = (Object[]) object;
			UserFeedbackCount userFeedbackCount = new UserFeedbackCount();
			userFeedbackCount.setAccount(objectArray[0].toString());
			if(objectArray[1].toString() == null && (objectArray[1].toString()).equals("")){
				userFeedbackCount.setEmail("");
			}else{
				userFeedbackCount.setEmail(objectArray[1].toString());
			}
			userFeedbackCount.setEmail(objectArray[1].toString());
			userFeedbackCount.setPositive(objectArray[2].toString());
			userFeedbackCount.setNegative(objectArray[3].toString());
			userFeedbackCount.setNeutral(objectArray[4].toString());
			feedbackCountList.add(userFeedbackCount);
		}
	}

	/**
	 * Search feedback.
	 *
	 * @return the string
	 */
	public String searchFeedback() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedback() - start"); //$NON-NLS-1$
		}

		populateUserCountList();

		if(itemId == null || itemId ==""){
			addActionError("Enter valid Item Id");
			return INPUT;
		} else if(userId.equals("")){
			addActionError("Enter valid User Id");
			return INPUT;
		}

		User user = UserServiceDelegator.getUserByUserId(userId);

		if(user == null){
			addActionError("User not found please try another");
			return INPUT;
		}

		if (user.getId() != null) {
			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute("itemId", Integer.parseInt(itemId));
			List<Items> items = (List<Items>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, Items.class);

			if(items.size() ==0){
				addActionError("Iteam not found please try another");
				return INPUT;
			}

			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute("itemId", items.size() > 0 ? items.get(0) : null);
			searchCriteria.setAttribute("userByFromUserId", user);

			Feedback listFeedback = FeedbackServiceDelegator
					.getFeedbackByUserItemId(searchCriteria);

			this.buyerComment = "";
			this.sellerComment = "";

			if(listFeedback.isNegative() == true){
				this.rating = -1;
			}else if(listFeedback.isNeutral() == true){
				this.rating = 0;
			}else if(listFeedback.isPositive() == true){
				this.rating = 1;
			}

			if (listFeedback.getId() != null) {
				if (listFeedback.getUserType().equalsIgnoreCase("B")) {
					this.buyerComment = listFeedback.getMessage();
				} else {
					this.sellerComment = listFeedback.getMessage();
				}
				this.feedbackId = listFeedback.getId();
			} else {
				addActionError("Record not found...");
			}
		} else {
			addActionError("User not found...");
		}

		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedback() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Update feedback.
	 *
	 * @return the string
	 */
	public String updateFeedback() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("updateFeedback() - start"); //$NON-NLS-1$
		}

		if(feedbackId == 0){
			addActionError("Enter item id and user id for update feedback comment");
			populateUserCountList();
			return INPUT;
		}

		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute("id", feedbackId);
		Feedback feedback = FeedbackServiceDelegator.getFeedbackListByUserId(searchCriteria).get(0);

		if(rating == 1){
			feedback.setPositive(true);
			feedback.setNeutral(false);
			feedback.setNegative(false);
		}else if(rating == 0){
			feedback.setNeutral(true);
			feedback.setPositive(false);
			feedback.setNegative(false);
		}else if(rating == -1){
			feedback.setNegative(true);
			feedback.setPositive(false);
			feedback.setNeutral(false);
		}else if(rating == -2){
			feedback.setNegative(false);
			feedback.setPositive(false);
			feedback.setNeutral(false);
		}

		if (feedback.getUserType().equalsIgnoreCase("B")) {
			feedback.setMessage(request.getParameter("buyerComment"));
		} else {
			feedback.setMessage(request.getParameter("sellerComment"));
		}
		populateUserCountList();
		addActionMessage("Update user comment successfully");
		FeedbackServiceDelegator.updateFeedback(feedback);

		if (logger.isDebugEnabled()) {
			logger.debug("updateFeedback() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String searchFeedbackRating() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedbackRating() - starts"); //$NON-NLS-1$
		}

		if(ratingUserId.equals("")){
			addActionMessage("Enter valid User Id for get rating");
			populateUserCountList();
			return INPUT;
		}

		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute("userByToUserId", UserServiceDelegator.getUserByUserId(ratingUserId));
		this.feedbacks = FeedbackServiceDelegator.getFeedbackListByUserId(searchCriteria);

		if(feedbacks.size() ==0){
			addActionError("User not get any Feedback");
			populateUserCountList();
			return INPUT;
		}

		for (Feedback feedback : feedbacks) {
			this.totalNegativeFeedback += (feedback.isNegative() ? 1 : 0);
			this.totalNeutralFeedback += (feedback.isNeutral() ? 1 : 0);
			this.totalPositiveFeedback += (feedback.isPositive() ? 1 : 0);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedbackRating() - end"); //$NON-NLS-1$
		}

		populateUserCountList();
		return SUCCESS;
	}

	@Override
	public void validate() {
		this.buyerComment = "";
		this.sellerComment = "";
		super.validate();
	}

	public String getItemId() {
		return itemId;
	}

	public void setItemId(String itemId) {
		this.itemId = itemId;
	}

	/**
	 * Gets the user id.
	 *
	 * @return the user id
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * Sets the user id.
	 *
	 * @param userId the new user id
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * Gets the buyer comment.
	 *
	 * @return the buyer comment
	 */
	public String getBuyerComment() {
		return buyerComment;
	}

	/**
	 * Sets the buyer comment.
	 *
	 * @param buyerComment the new buyer comment
	 */
	public void setBuyerComment(String buyerComment) {
		this.buyerComment = buyerComment;
	}

	/**
	 * Gets the seller comment.
	 *
	 * @return the seller comment
	 */
	public String getSellerComment() {
		return sellerComment;
	}

	/**
	 * Sets the seller comment.
	 *
	 * @param sellerComment the new seller comment
	 */
	public void setSellerComment(String sellerComment) {
		this.sellerComment = sellerComment;
	}

	/**
	 * Gets the feedback id.
	 *
	 * @return the feedback id
	 */
	public int getFeedbackId() {
		return feedbackId;
	}

	/**
	 * Sets the feedback id.
	 *
	 * @param feedbackId the new feedback id
	 */
	public void setFeedbackId(int feedbackId) {
		this.feedbackId = feedbackId;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * @return the feedbackCountList
	 */
	public List<UserFeedbackCount> getFeedbackCountList() {
		return feedbackCountList;
	}

	/**
	 * @param feedbackCountList the feedbackCountList to set
	 */
	public void setFeedbackCountList(List<UserFeedbackCount> feedbackCountList) {
		this.feedbackCountList = feedbackCountList;
	}

	public String getRatingUserId() {
		return ratingUserId;
	}

	public void setRatingUserId(String ratingUserId) {
		this.ratingUserId = ratingUserId;
	}

	public int getRating() {
		return rating;
	}

	public void setRating(int rating) {
		this.rating = rating;
	}
}